<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <div style="margin: 14px">
      <a-input v-model:value="searchValue" allowClear placeholder="搜索" />
      <a-tree
        @select="handleSelect"
        :tree-data="treeData"
        :expanded-keys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        @expand="onExpand"
        :field-names="{ children: 'children', title: 'name', key: 'id' }"
      >
        <template #title="{ name }">
          <span v-if="name.indexOf(searchValue) > -1">
            {{ name.substr(0, name.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ name }}</span>
        </template>
      </a-tree>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'DeptTree',
};
</script>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';

import { getDeptList } from '/@/api/sys/system';

const emit = defineEmits(['select']);
const treeData = ref([]);

//展开的key
const expandedKeys = ref([]);
//搜索关键字
const searchValue = ref('');
//是否展开树
const autoExpandParent = ref(true);

// 展开收起触发
const onExpand = (keys) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

async function fetch() {
  treeData.value = await getDeptList();
  expandedKeys.value.push(treeData.value[0]?.id);
}

function handleSelect(keys) {
  emit('select', keys[0]);
}

onMounted(() => {
  fetch();
});

const getExpandedKeys = (value, keys, tree) => {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      getExpandedKeys(value, keys, node.children);
    }
    if (node.name.indexOf(value) > -1) {
      keys.push(node.id);
    }
  }
  return keys;
};

//搜索事件
watch(searchValue, (value) => {
  if (!value) return (autoExpandParent.value = false);
  expandedKeys.value = [...getExpandedKeys(value, [], treeData.value), treeData.value[0]?.id];
  autoExpandParent.value = true;
});
</script>
